package com.cf.invoker.http.server;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/****
 *
 * 服务注册
 * @Author zhu-mingming
 * @Description
 * @Date 2018/10/23
 *
 **/

@Slf4j
public class ServiceRegisterStore {

    private Map<String, ServiceMeta> serviceMetaMap = new ConcurrentHashMap<String, ServiceMeta>();

    /**
     * 注册服务
     *
     * @param serviceMeta
     * @return
     */
    private ServiceMeta registerServiceMeta(ServiceMeta serviceMeta) {
        if (serviceMeta != null && StringUtils.isNotBlank(serviceMeta.getKey())) {
            ServiceMeta rg = serviceMetaMap.putIfAbsent(serviceMeta.getKey(), serviceMeta);
            if (rg != null) {
                throw new IllegalArgumentException(serviceMeta.getKey() + "已经被注册为" + rg.getMethodParentBean().getClass().getName() + "注册");
            }
        }
        return serviceMeta;
    }

    /**
     * 注册服务
     *
     * @param bean
     * @return
     */
    void registerServiceMetas(Object bean) {

        Class<?>[] interfaces = bean.getClass().getInterfaces();

        for (Class<?> intfacee : interfaces) {
            Method[] methods = intfacee.getMethods();

            if (null == methods) {
                return;
            }

            for (Method mt : methods) {
                ServiceMeta smd = new ServiceMeta();
                smd.setHasArguments(mt.getParameterCount() > 0).setHasReturn(mt.getReturnType() != null).setMethodParentBean(bean);

                //设置是否有返回类型
                if (smd.isHasReturn()) {
                    smd.setResponseType(mt.getReturnType());
                }

                //设置时候有返回参数
                if (smd.isHasArguments()) {
                    smd.setArgumentTypes(Arrays.asList(mt.getParameterTypes()));
                }
                smd.setKey(mt.getDeclaringClass().getName() + "." + mt.getName());
                smd.setMethod(mt);
                registerServiceMeta(smd);
            }
        }


    }


    /**
     * 获取服务
     *
     * @param key
     * @return
     */
    ServiceMeta getMethod(String key) {
        return serviceMetaMap.get(key);
    }

    int getSize() {
        return serviceMetaMap.size();
    }
}
